﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace SignalBox.Core.Model.Timetable
{
    public class Timetable
    {

        private List<TrainSchedule> schedules;
        private List<TrainType> trainTypes;

        public string Name
        {
            get;
            set;
        }

        public string StartTime
        {
            get;
            set;
        }

        public TrackLayout TrackLayout
        {
            get;
            set;
        }

        public string FileName
        {
            get;
            set;
        }

        public Timetable(TrackLayout tl)
        {
            TrackLayout = tl;
            schedules = new List<TrainSchedule>();
            trainTypes = new List<TrainType>();
        }

        public TrainType FindTrainType(string code)
        {
            var q = (from TrainType t in trainTypes
                    where t.TypeCode == code
                    select t).FirstOrDefault<TrainType>();

            return q;
        }

        public List<TrainType> TrainTypes
        {
            get { return trainTypes; }
        }

        public List<TrainSchedule> TrainSchedules
        {
            get { return schedules; }
        }

        public void Save()
        {

            XDocument doc = new XDocument();

            XElement elem = new XElement("Timetable",
                new XElement("Name", Name),
                new XElement("StartTime", StartTime),
                new XElement("TrainTypes",
                    from TrainType tt in TrainTypes
                    select new XElement("TrainType",
                        new XElement("Code", tt.TypeCode),
                        new XElement("MaxSpeed", tt.MaxSpeed))),
                new XElement("TrainSchedules",
                    from TrainSchedule ts in TrainSchedules
                    select ts.ToXml()));

            doc.Add(elem);
            doc.Save(FileName);

        }

        public void Load()
        {
            XDocument doc = XDocument.Load(FileName);
            Name = doc.Root.Element("Name").Value;
            StartTime = doc.Root.Element("StartTime").Value;

            foreach (XElement elem in doc.Root.Element("TrainTypes").Elements("TrainType"))
            {
                TrainType tt = new TrainType();
                tt.TypeCode = elem.Element("Code").Value;
                tt.MaxSpeed = Int32.Parse(elem.Element("MaxSpeed").Value);
                TrainTypes.Add(tt);
            }

            foreach (XElement elem in doc.Root.Element("TrainSchedules").Elements("TrainSchedule"))
            {
                TrainSchedule sched = new TrainSchedule();
                sched.Timetable = this;
                sched.FromXml(elem);
                schedules.Add(sched);


            }
        }
    }
}
